/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { ChildPlaneCommandProps } from './types';

type FormDataType = {
  type: number;
  point1: pickedVertexData;
  point2: pickedVertexData;
  point3: pickedVertexData;
};

export function ThreePoint({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) {
  const initData = {
    type: 0,
    point1: undefined,
    point2: undefined,
    point3: undefined,
  };
  const [formData, setFormData] = useState<FormDataType>(initData);

  // 0整圆 1顺时针 2逆时针

  const { picker } = useTools();

  useEffect(() => {
    onExecute();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const points = props?.params?.points;
      const reverse = props?.params?.reverse;
      const mode = props?.params?.mode;

      await initEditDependency([...points]);

      const defaultType = mode === 'circle-3point' ? 0 : reverse ? 2 : 1;

      const defaultPoint1 = points
        ? (picker.generatePickObjByPickID(points[0]) as pickedVertexData)
        : undefined;
      const defaultPoint2 = points
        ? (picker.generatePickObjByPickID(points[1]) as pickedVertexData)
        : undefined;
      const defaultPoint3 = points
        ? (picker.generatePickObjByPickID(points[2]) as pickedVertexData)
        : undefined;
      setFormData({
        type: defaultType,
        point1: defaultPoint1,
        point2: defaultPoint2,
        point3: defaultPoint3,
      });
    }
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    const { point1, point2, point3 } = formData;
    if (isEmpty(point1) || isEmpty(point2) || isEmpty(point3)) {
      return;
    }
    await onExecute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, isLoading, clear, confirmCommand } =
    useCommand('cmd-arc', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const onExecute = async (preview: boolean = true) => {
    const { type, point1, point2, point3 } = formData;
    if (isEmpty(point1) || isEmpty(point2) || isEmpty(point3)) {
      clear();
      return;
    }

    const points = [point1.vertexId, point2.vertexId, point3.vertexId];

    const params =
      type === 0
        ? {
            mode: 'circle-3point',
            points: points,
          }
        : type === 1
          ? {
              mode: '3point',
              points: points,
              reverse: false,
            }
          : {
              mode: '3point',
              points: points,
              reverse: true,
            };

    await confirmCommand(
      {
        type: 'ArcOfCircle',
        a: params,
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      point1: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      point2: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      point3: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      type: {
        title: '圆限制',
        type: 'number',
        oneOf: [
          {
            type: 'number',
            title: '整圆',
            const: 0,
          },
          {
            type: 'number',
            title: '顺时针',
            const: 1,
          },
          {
            type: 'number',
            title: '逆时针',
            const: 2,
          },
        ],
        default: 0,
      },
    },
  };

  const isFormDataValid = () => {
    const { point1, point2, point3 } = formData;
    return point1 != null && point2 != null && point3 != null;
  };

  const extraUiSchema = {
    point1: {
      'ui:placeholder': '请输入点1',
      'ui:autofocus': true,
    },
    point2: {
      'ui:placeholder': '请输入点2',
    },
    point3: {
      'ui:placeholder': '请输入点3',
    },
  };

  return (
    <NonDialogPickableCommandForm
      isFormDataValid={isFormDataValid()}
      disabled={initingEdit}
      className='-mt-3'
      submitLoading={isLoading}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          type: v.type,
          point1: v.point1,
          point2: v.point2,
          point3: v.point3,
        };
        setFormData(data);
      }}
      extraUiSchema={extraUiSchema}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
